
import sys
import re

def read_fcf_file(path, encoding=sys.getfilesystemencoding()):
	with open(path) as stream:
		return read_fcf(stream, encoding)

def read_fcf(stream, encoding=sys.getfilesystemencoding()):
	if isinstance(stream, basestring):
		text = stream
	else:
		text = stream.read()
	if not isinstance(text, unicode):
		if len(text) >= 2 and text[:2] == '\xff\xfe':
			text = text.decode('utf-16le')[1:]
		else:
			text = text.decode(encoding)
	lines = re.split(r'[\r\n]+', text.strip())
	title = lines[0].strip()
	lines = lines[1:]
	lines = [line for line in lines if re.match(r'\d+;.*', line)]

	flow = {}
	for line in lines:
		pm = line.split(';')
		pm = pm[1].split("'")

		ruletype = pm[0]
		index = int(pm[1])
		left = int(pm[2])
		top = int(pm[3])
		right = int(pm[4])
		width = right - left
		bottom = int(pm[5])
		height = bottom - top
		# pm[6] # XXX: ???
		assert pm[7] == '16777215'
		assert pm[8] == '0'
		assert pm[9] == '0'

		if pm[0] == 'SCENE':
			title = pm[10]
			jump = []
			for i in range(int(pm[11])):
				pm1 = pm[12+i].split(':')
				assert pm1[0] == '0' or pm1[0] == '1' or pm1[0] == '2'
				conditions = []
				for k in range(int(pm1[0])):
					condition = pm1[1+k].split('//')
					assert len(condition) == 3
					condition[1] = ['==', '!=', '<', '>', '<=', '>='][int(condition[1])]
					condition[2] = int(condition[2])
					conditions.append(condition)
				and_or = {'1':'and', '2':'or'}[pm1[-3]]
				target = int(pm1[-2])
				# XXX: pm[-1]?
				jump.append({'condition': conditions, 'condition_op': and_or, 'target': target})
			assert len(jump) in [0, 1, 2, 3]
			last = pm[12+len(jump)]
			flagoperation = []
			if last != '0':
				pm = last.split(':')
				for i in range(int(pm[0])):
					update = pm[1+i].split('//')
					assert len(update) == 3
					flagoperation.append([update[0], {'1':'+', '2':'-', '3':'='}[update[2]], int(update[1])])
			flow[index] = {'type': ruletype, 'jump': jump, 'flagoperation': flagoperation, 'title': title}
		elif pm[0] == 'SELECTER':
			title = pm[10]
			alternative = []
			for i in range(int(pm[11])):
				# XXX: pm[12+i*3+1]
				alternative.append({'text': pm[12+i*3+2], 'target': int(pm[12+i*3])})
			flow[index] = {'type': ruletype, 'alternative': alternative, 'title': title}
		elif pm[0] == 'OUTERLABEL':
			title = pm[12]
			assert title == ''
			file = pm[10]
			target = int(pm[11]) # XXX: what is target used for?
			flow[index] = {'type': ruletype, 'file': file, 'target': target}
	return flow


